package com.infodeli.user.dialog.service.impl;

import com.infodeli.common.exception.ExceptionEnum;
import com.infodeli.common.utils.ComTool;
import com.infodeli.common.utils.ServiceExceptionUtils;
import com.infodeli.user.dialog.vo.DialogRelationVo;
import com.infodeli.user.login.entity.UserEntity;
import com.infodeli.user.login.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.infodeli.common.utils.PageUtils;
import com.infodeli.common.utils.Query;

import com.infodeli.user.dialog.dao.DialogRelationDao;
import com.infodeli.user.dialog.entity.DialogRelationEntity;
import com.infodeli.user.dialog.service.DialogRelationService;
import org.springframework.util.concurrent.CompletableToListenableFutureAdapter;


@Service("dialogRelationService")
//@Service
public class DialogRelationServiceImpl extends ServiceImpl<DialogRelationDao, DialogRelationEntity> implements DialogRelationService {

    @Autowired
    UserService userService;

    @Override // 管理员查询对话
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        if(key != null && !"".equals(key)){

        }
        IPage<DialogRelationEntity> page = baseMapper.queryPageAdmin(
                new Query<DialogRelationEntity>().getPage(params),
                new QueryWrapper<DialogRelationEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 分页查询 某个用户的所有id
     * 我认为，这个进行两次查询也是可以的，
     * 因为你一次查，也是要进行三个表的关联操作的，对话中两个用户的信息都需要查询。
     */
    @Override // 分页查询
    public PageUtils queryPageByUid(Map<String, Object> params, Long uid) {
        QueryWrapper<DialogRelationEntity> wrapper = new QueryWrapper<>();
        if(params != null && params.get("key") != null){
            String key = (String)params.get("key");
        }
        wrapper.and(w -> w.eq("user_send", uid).eq("show_status_send", 1))
                .or(w-> w.eq("user_recv", uid).eq("show_status_recv",1));
        // 获取所有 关于 uid 的对话
        //List<DialogRelationEntity> list = this.list(wrapper);
        IPage<DialogRelationEntity> page = page(new Query<DialogRelationEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<DialogRelationEntity> list = (List<DialogRelationEntity>) pageUtils.getList();
        if(list == null || list.size() == 0){
            return null;
        }

        // 因为要知道另一个人的相关信息，先收集 另一个人的uid
        List<Long> uidList = list.stream().map( entity -> {
            if(entity.getUserSend() != uid){
                return entity.getUserSend();
            }else{
                return entity.getUserRecv();
            }
        }).collect(Collectors.toList());

        // 查询 另一个人的所有信息，并保存在map中，方便快速查找
        List<UserEntity> userEntities = (List)userService.listByIds(uidList);
        Map<Long, UserEntity> map = new HashMap<>();
        for(UserEntity entity : userEntities){
            map.put(entity.getUid(), entity);
        }

        // 核心：封装相关信息到 对应的vo 中
        List<DialogRelationVo> voList = list.stream().map( entity -> {
            UserEntity userEntity;
            if(entity.getUserSend() != uid){
                userEntity = map.get(entity.getUserSend());
            }else{
                userEntity = map.get(entity.getUserRecv());
            }
            DialogRelationVo vo = new DialogRelationVo();
            vo.setDialId(entity.getDialId());
            vo.setNickName(userEntity.getNickName());
            vo.setUid(userEntity.getUid());
            vo.setPortrait(userEntity.getPortrait());
            if(uid == entity.getUnreadId()){
                vo.setUnreadNum(entity.getUnreadNum());
            }else{
                vo.setUnreadNum(0);
            }
            vo.setNewContent(entity.getNewContent());
            return vo;
        }).collect(Collectors.toList());


        // 返回所有的vo
        pageUtils.setList(voList);

        return pageUtils;
    }

    // 增加
    public void addDialogRelation(Long fromId, Long toId){
        // 两种可能：1、新建，2、修改我的showStatus
        QueryWrapper<DialogRelationEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_send",Math.min(fromId,toId)).eq("user_recv", Math.max(fromId, toId));
        DialogRelationEntity one = this.getOne(wrapper);
        DialogRelationEntity newEntity = new DialogRelationEntity();
        if(one == null){ // 1、新建
            newEntity.setUserSend(Math.min(fromId, toId));
            newEntity.setUserRecv(Math.max(fromId, toId));
            String dateStr = ComTool.getDateStr();
            newEntity.setCreateTime(dateStr);
            newEntity.setNewTime(dateStr);
            newEntity.setUnreadId(0L);
            newEntity.setUnreadNum(0);
            if(fromId == newEntity.getUserSend()){
                newEntity.setShowStatusSend(1);
                newEntity.setShowStatusRecv(0);
            }else{
                newEntity.setShowStatusSend(0);
                newEntity.setShowStatusRecv(1);
            }
            newEntity.setNewContent("");
            this.save(newEntity);

        }else{ // 2、修改我的 status 以及 newTime
            // 这里设置newTime可能对导致 对方的 列表中 莫名置顶对话
            newEntity.setDialId(one.getDialId());
            newEntity.setNewTime(ComTool.getDateStr());
            if(fromId == one.getUserSend()){
                newEntity.setShowStatusSend(1);
            }else{
                newEntity.setShowStatusRecv(1);
            }
            this.updateById(newEntity);
        }
    }

    @Override // 删除：修改 用户的对应的 showStatus
    public void deleteByUid(Long dialId, Long uid) {
        updateShowStatus(dialId, uid, 0);
    }

    @Override // info：获取一个的对话关系
    public DialogRelationVo getVoById(Long dialId, Long uid) {
        DialogRelationEntity byId = this.getById(dialId);
        Long otherId = null;
        if(byId.getUserSend() == uid){
            otherId = byId.getUserRecv();
        }else if(byId.getUserRecv() == uid){
            otherId = byId.getUserSend();
        }else{
            throw ServiceExceptionUtils.getServiceException(ExceptionEnum.ALL_ERROR);
        }
        UserEntity user = userService.getById(otherId);

        DialogRelationVo vo = new DialogRelationVo();
        vo.setDialId(byId.getDialId());
        vo.setUid(user.getUid());
        vo.setNickName(user.getNickName());
        vo.setPortrait(user.getPortrait());
        if(byId.getUnreadId() == uid){
            vo.setUnreadNum(byId.getUnreadNum());
        }else{
            vo.setUnreadNum(0);
        }
        vo.setNewContent(byId.getNewContent());

        return vo;
    }

    // 真实 的 修改 showStatus
    public void updateShowStatus(Long dialId, Long uid, Integer showStatus){
        DialogRelationEntity updateEntity = new DialogRelationEntity();

        DialogRelationEntity drEntity = this.getById(dialId);
        if(drEntity.getUserSend() == uid){
            updateEntity.setShowStatusSend(showStatus);
        }else{
            updateEntity.setShowStatusRecv(showStatus);
        }
        updateEntity.setDialId(dialId);

        this.updateById(updateEntity);
    }




}